"""
作者：李伟丽
日期：2022/09/09
"""
import pymysql


# 数据库工具类
class DBUtil(object):
    conn = None

    @classmethod
    def __get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host="127.0.0.1", user="root", password="root", database="tpshop2.0",
                                       charset="utf8")
        # 返回非空连接
        return cls.conn

    @classmethod
    def __close_conn(cls):
        # 判断 conn 不为空，需要关闭
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None

    # 常用方法：查询一条
    @classmethod
    def select_one(cls, sql):
        cursor = None
        res = None
        try:
            cls.conn = cls.__get_conn()
            cursor = cls.conn.cursor()
            cursor.execute(sql)
            res = cursor.fetchone()
            print("查询结果为：", res)
        except Exception as e:
            print("查询sql错误：", str(e))
        finally:
            cursor.close()
            cls.__close_conn()
        return res

    # 常用方法：增删改
    @classmethod
    def uid(cls, sql):
        cursor = None
        try:
            cls.conn = cls.__get_conn()
            cursor = cls.conn.cursor()
            # 执行语句
            cursor.execute(sql)
            # 影响行数
            print("影响的行数：", cls.conn.affected_rows())
            # 提交事务
            cls.conn.commit()
        except Exception as e:
            # 回滚事务
            cls.conn.rollback()
            print("增删改sql执行失败：", str(e))
        finally:
            cursor.close()
            cls.__close_conn()

#
# if __name__ == '__main__':
#     DBUtil.select_one("select * from tp_users where mobile = '13800000000'")
#     DBUtil.uid("update tp_users set qq = '919127384' where mobile = '13800138006'")
